package com.clinic.exception;


import com.clinic.vo.ActionResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @CrossOrigin
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Object handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACES");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Accept,Origin,X-Requested-With,Content-Type,X-Auth-Token");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        String message = e.getMessage();
        if (message == null || "".equals(message)) {
            message = "用户权限异常";
            return new ActionResult(101, message, null);
        }
        return new ActionResult(500, "服务器错误", null);
    }
}
